package system

import (
	"context"
	"gf-assistant/internal/common/consts"
	"gf-assistant/internal/common/factory"
	"gf-assistant/internal/system/parameter"
	"github.com/gogf/gf/v2/util/gconv"
	"reflect"
)

type RoleService struct {
	userDao string
	roleDao string
}

func init() {
	roleService := RoleService{
		userDao: "system.UserDao",
		roleDao: "system.RoleDao",
	}
	factory.Put(reflect.TypeOf(roleService).String(), &roleService)
}
func (s *RoleService) GetRoleDao() *RoleDao {
	return factory.Get(s.roleDao).(*RoleDao)
}
func (s *RoleService) ListRole(ctx context.Context, req *parameter.ListRoleReq) (res *parameter.ListRoleRes) {

	if req.Page <= 1 {
		req.Page = 1
	}
	if req.Size == 0 {
		req.Size = 10
	}
	users := s.GetRoleDao().ListRole(ctx, req)
	count := s.GetRoleDao().CountRole(ctx, req)
	res = &parameter.ListRoleRes{
		Total:  count,
		Detail: users,
	}
	return res
}

// SaveRole  创建成员
func (s *RoleService) SaveRole(ctx context.Context, req *parameter.SaveRoleReq) (res *parameter.SaveRoleRes) {
	req.SetOperatorId(gconv.Uint(ctx.Value(consts.ContextKeyUserId)))
	//开启事务
	tx, err := s.GetRoleDao().DB().Begin(ctx)
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			panic("角色已经存在")
		} else {
			err := tx.Commit()
			if err != nil {
				return
			}
		}
	}()
	res = s.GetRoleDao().SaveRole(tx, req)
	s.GetRoleDao().SaveRoleMenu(tx, res.RoleId, req.MenuIds, req.GetOperatorId())
	return res
}

func (s *RoleService) DeleteRole(ctx context.Context, req *parameter.DeleteRoleReq) (res *parameter.DeleteRoleRes) {
	if req.RoleId == 0 {
		panic("角色ID必填")
	}
	req.SetOperatorId(gconv.Uint(ctx.Value(consts.ContextKeyUserId)))
	//开启事务
	tx, err := s.GetRoleDao().DB().Begin(ctx)
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			panic("角色删除失败")
		} else {
			err := tx.Commit()
			if err != nil {
				return
			}
		}
	}()
	s.GetRoleDao().DeleteRole(tx, req)
	return res
}
